package com.itbaizhan.springsecuritydemo1.Contorller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Controller
@ResponseBody
public class SessionRegistry {
    @Autowired
    private org.springframework.security.core.session.SessionRegistry sessionRegistry;
    
    @GetMapping("/kickout")
    public void kickOutUser (String username){
        //遍历所有登录用户
        List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
        //遍历所有用户，知道找出需要删除的用户
        for (Object principal : allPrincipals) {
            UserDetails userDetails = (UserDetails) principal;
            if (username.equals(userDetails.getUsername())){
                //拿到所有会话不包括过期会话
                List<SessionInformation> allSessions = sessionRegistry.getAllSessions(userDetails, false);
                if ( null!= allSessions && !allSessions.isEmpty()){  //如果长度不为0并且不为空
                    for (SessionInformation session : allSessions) {
                        //立即失效
                        session.expireNow();
                    }
                }
            }
        }
    }
}
